package com.koron.car.web.authorized.service.impl;

import com.koron.bean.system.staff.vo.EamUser;
import com.koron.car.config.Constants;
import com.koron.car.web.authorized.bean.entity.CarDelimit;
import com.koron.car.web.authorized.bean.entity.CarNumberBind;
import com.koron.car.web.authorized.bean.vo.CarDelimitMsgVO;
import com.koron.car.web.authorized.mapper.CarDelimitMapper;
import com.koron.car.web.authorized.mapper.CarNumberBindMapper;
import com.koron.car.web.authorized.service.CarDelimitService;
import com.koron.car.web.carledger.bean.vo.CarVO;
import com.koron.car.web.carledger.mapper.CarMapper;
import com.koron.car.web.common.CommonUtils;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * (CarDelimit)表服务实现类
 *
 * @author makejava
 * @since 2022-04-06 14:42:21
 */
@Service
public class CarDelimitServiceImpl implements CarDelimitService {

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    @TaskAnnotation("queryById")
    public CarDelimit queryById(SessionFactory factory, String id) {
        CarDelimitMapper mapper = factory.getMapper(CarDelimitMapper.class);
        return mapper.queryById(id);
    }

    /**
     * 列表查询
     *
     * @param delimit 筛选条件
     * @return 查询结果
     */
    @Override
    @TaskAnnotation("queryList")
    public List<CarDelimit> queryList(SessionFactory factory, CarDelimit delimit) {
        CarDelimitMapper mapper = factory.getMapper(CarDelimitMapper.class);
        return mapper.queryList(delimit);
    }

    /**
     * 新增数据
     * @param delimit 实例对象
     * @return 实例对象
     */
    @Override
    @TaskAnnotation("insert")
    public CarDelimit insert(SessionFactory factory, CarDelimit delimit) {
        CarDelimitMapper mapper = factory.getMapper(CarDelimitMapper.class);
        delimit.setId(CodeTools.getCode32());
        Assert.isTrue(checkPrepareNumber(delimit.getPrepareNumber()), "定编号不合法");
        mapper.insert(delimit);
        return delimit;
    }

    /**
     * 修改数据
     * @param delimit 实例对象
     * @return 实例对象
     */
    @Override
    @TaskAnnotation("update")
    public CarDelimit update(SessionFactory factory, CarDelimit delimit) {
        CarDelimitMapper mapper = factory.getMapper(CarDelimitMapper.class);
        Assert.isTrue(checkPrepareNumber(delimit.getPrepareNumber()), "定编号不合法");
        mapper.update(delimit);
        return queryById(factory, delimit.getId());
    }

    @Override
    @TaskAnnotation("saveOrUpdate")
    public int saveOrUpdate(SessionFactory factory, List<CarDelimit> delimits) {
        CarDelimitMapper mapper = factory.getMapper(CarDelimitMapper.class);
        CommonUtils.sorted(delimits);
        delimits.stream().forEach(row -> {
            checkPrepareNumber(row.getPrepareNumber());
            row.setId(StringUtils.isBlank(row.getId()) ? CodeTools.getCode32() : row.getId());
        });
        return mapper.insertOrUpdateBatch(delimits);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    @TaskAnnotation("deleteById")
    public boolean deleteById(SessionFactory factory, String id) {
        CarDelimitMapper mapper = factory.getMapper(CarDelimitMapper.class);
        return mapper.deleteById(id) > 0;
    }

    @Override
    public int clean(SessionFactory factory) {
        CarDelimitMapper mapper = factory.getMapper(CarDelimitMapper.class);
        return mapper.clean();
    }

    @Override
    @TaskAnnotation("getDelimitNum")
    public List<CarDelimitMsgVO> getDelimitNum(SessionFactory factory, String type, String state) {
        CarDelimitMapper mapper = factory.getMapper(CarDelimitMapper.class);
        return mapper.getDelimitNum(type, state);
    }

    @Override
    @TaskAnnotation("bind")
    public CarNumberBind bind(SessionFactory factory, CarNumberBind bind) {
        Assert.hasText(bind.getPrepareNumber(), "定编号不能为空");
        Assert.hasText(bind.getCarId(), "车辆id不能为空");
        CarNumberBindMapper bindMapper = factory.getMapper(CarNumberBindMapper.class);
        CarDelimitMapper mapper = factory.getMapper(CarDelimitMapper.class);
        CarMapper carMapper = factory.getMapper(CarMapper.class);
        EamUser eamUser = ThreadLocalContext.get();
        CommonUtils.update(bind, eamUser);
        bind.setId(CodeTools.getCode32());
        bind.setDeptId(eamUser.getOrgId());
        // 设置绑定的状态
        bind.setState(Constants.BindState.BINDING);
        CarDelimit query = new CarDelimit();
        query.setPrepareNumber(bind.getPrepareNumber());
        List<CarDelimit> carDelimits = mapper.queryList(query);
        Assert.isTrue(CollectionUtils.size(carDelimits) == 1, "定编号有且仅能有一个");
        CarDelimit delimit = carDelimits.get(0);
        // 设置定编号的状态
        delimit.setState(Constants.DelimitState.BINDING);
        mapper.update(delimit);
        // 设置车辆的定编号
        CarVO carVO = carMapper.queryById(bind.getCarId());
        Assert.notNull(carVO, "车辆不存在");
        carVO.setPrepareType(bind.getPrepareType());
        carVO.setPrepareNumber(bind.getPrepareNumber());
        carMapper.saveOrUpdate(carVO);
        bindMapper.insert(bind);
        return bind;
    }

    @Override
    @TaskAnnotation("getBindById")
    public CarNumberBind getBindById(SessionFactory factory, String bindId) {
        CarNumberBindMapper bindMapper = factory.getMapper(CarNumberBindMapper.class);
        return bindMapper.queryById(bindId);
    }

    /**
     * 检测定编号是否合法
     * @param prepareNumber
     * @return
     */
    boolean checkPrepareNumber(String prepareNumber) {
        if(StringUtils.isBlank(prepareNumber)) {
            return false;
        }
        List<String> nums = new ArrayList<>(Constants.PrepareType.typeMap.values());
        if(!nums.contains(prepareNumber.substring(0, 2))) {
            // 前缀不合法
            return false;
        }
        for (String str : nums) {
            prepareNumber = prepareNumber.replace(str, "");
        }
        try {
            // 范围不合法
            int number = Integer.parseInt(prepareNumber);
            return number > 0 && number <= 1000;
        } catch (Exception e) {
            // 类型不合法
            return false;
        }
    }
}
